<?php
/**
 * 抽奖奖品
 * User: cxm
 * Date: 2020/9/23
 * Time: 17:46
 */
namespace App\Http\Controllers\Admin\Activity;
use App\Http\Controllers\Admin\Controller;
use App\Models\Activity;
use App\Models\AwardGoods;
use App\Models\AwardGoodsClass;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Http\Request;

class AwardGoodsController extends Controller {
    /**
     * 奖品列表
     * URL POST:/admin/activity/goods/getLists
     * @param Request $request
     * @param int activity_id 活动ID
     * @param string keyword 奖品名称
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['activity_id','keyword','page','limit']);
        if (!array_key_exists('activity_id',$params) || empty($params['activity_id'])) {
            return $this->error('缺少活动ID');
        }
        $params['where'][] = ['activity_id',$params['activity_id']];
        // 关键字查询
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            $params['where'][] = ['name','like','%'.$keyword.'%'];
        }
        $params['orderBy'] = ['sort asc','created_at desc'];
        // 活动
        $params['with'][] = 'activity:id,name';
        // 图片
        $params['with'][] = 'file:id,path';
        $data = AwardGoods::listByWhere($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 奖品详情
     * URL POST:/admin/activity/goods/detail
     * @param Request $request
     * @param int goods_id 奖品ID
     * @return mixed
     */
    public function detail(Request $request){
        $params = $request->only(['goods_id']);
        if (!array_key_exists('goods_id',$params) || empty($params['goods_id'])) {
            return $this->error('缺少奖品ID');
        }
        $params['where'][] = ['id',$params['goods_id']];
        $params['with'][] = 'goods';
        $params['with'][] = 'file:id,path';
        $info = AwardGoods::detailsWith($params);
        return $this->success('操作成功',$info);
    }

    /**
     * 奖品添加、编辑处理
     * URL POST:/admin/activity/goods/store
     * @param Request $request
     * @param int id 奖品ID 编辑时必须
     * @param int type 1单独的奖品 2 选择种类 （例：奖品为农产品，中奖后选择苹果、梨子、香蕉……）
     * @param array goods 奖品下的类别名称
     * @param int activity_id 活动ID
     * @param string name 奖品名称
     * @param string short_name 简称
     * @param string describe 奖品介绍
     * @param int num 用户获取相应奖品的数量
     * @param int img 奖品图片
     * @param int stock 奖品数量
     * @param int probability 中奖概率 整数
     * @param int max_num 多少次必中 0 代表不限
     * @param int sort 排序
     * @param int is_get 是否需要领取 1否 2填写地址 3手机
     * @param int is_prize 是否可以参与第二次抽奖 1是 2否
     * @return mixed
     */
    public function store(Request $request){
        $params = $request->only(['id','type','goods','activity_id','describe','name','short_name','num','img','stock','probability','max_num','sort','is_get','is_prize']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $type = isset($params['type']) ? $params['type'] : 1;
        $validator = Validator::make($params,[
            'activity_id'               => ['required'],
            'name'                      => ['required'],
            'short_name'                => ['required'],
            'describe'                  => ['required'],
            //'img'                       => ['required','integer'],
            'stock'                     => ['required','integer'],
            'probability'               => [ 'required','integer'],
            'goods'                     => [$type == 2 ? 'required' : 'nullable']
        ],[
            'activity_id.required'      => '缺少活动ID',
            'name.required'             => '奖品名称是必须的',
            'short_name.required'       => '简称是必须的',
            'describe.required'         => '奖品介绍是必须的',
            //'img.required'              => '奖品图片是必须的',
            //'img.integer'               => '图片参数错误',
            'stock.required'            => '奖品数量是必须的',
            'stock.integer'             => '奖品数量值为正整数',
            'probability.required'      => '中奖概率是必须的',
            'probability.integer'       => '中奖概率值为正整数',
            'goods.required'            => '请设置奖品的分类物品'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        // 活动信息
        $activity = Activity::find( $params['activity_id'] );
        if ($id == 0) {
            $goods = new AwardGoods();
            // 查看奖品数量
            if ($goods->where('activity_id',$params['activity_id'])->count() >= $activity->goods_num) {
                return $this->error('该活动的奖品数量为'.$activity->goods_num);
            }
        }else{
            $goods = AwardGoods::find($id);
            if (!$goods) {
                return $this->error('奖品不存在');
            }
        }
        DB::beginTransaction();
        try{
            $goods->type                        = $type;
            $goods->activity_id                 = $params['activity_id'];
            $goods->name                        = $params['name'];
            $goods->short_name                  = $params['short_name'];
            $goods->describe                    = $params['describe'];
            $goods->num                         = isset($params['num']) ? $params['num'] : 1;
            $goods->img                         = isset($params['img']) ? $params['img'] : '';
            if ($type == 1) {
                $goods->stock                       = $params['stock'];
                $goods->un_stock                    = $params['stock']; // 未领取的数量
            }
            $goods->probability                 = $params['probability'];
            $goods->max_num                     = isset($params['max_num']) ? $params['max_num'] : 0;
            $goods->sort                        = isset($params['sort']) ? $params['sort'] : 1;
            $goods->is_get                      = isset($params['is_get']) ? $params['is_get'] : 1;
            $goods->is_prize                    = isset($params['is_prize']) ? $params['is_prize'] : 1;
            if ($goods->save()) {
                // 需要添加奖品分类物品时
                if ($type == 2) {
                    // 删除之前的奖品
                    AwardGoodsClass::where('award_goods_id',$goods->id)->forceDelete();
                    $data = [];
                    // 库存
                    $stock = 0;
                    foreach ($params['goods'] as $item) {
                        $stock+=$item['stock'];
                        $data[] = [
                            'award_goods_id'        => $goods->id,
                            'name'                  => $item['name'],
                            'stock'                 => $item['stock'],
                            'un_stock'              => $item['stock'],
                            'sort'                  => $item['sort'],
                            'created_at'            => Carbon::now()
                        ];
                    }

                    $classInsert = AwardGoodsClass::insert($data);
                    if ($classInsert ===  false) {
                        DB::rollBack();
                        return $this->error('奖品分类商品添加失败');
                    }
                    // 修改奖品的总库存
                    $w = [];
                    $w[] = ['id',$goods->id];
                    $field = [
                        'stock'     => $stock,
                        'un_stock'  => $stock
                    ];
                    $modify = AwardGoods::modify($w,$field);
                    if ($modify === false) {
                        DB::rollBack();
                        return $this->error('修改总库存失败');
                    }
                }
            }
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return  $this->error('操作失败');
        }

        return $this->success('操作成功');
    }

    /**
     * 删除
     * URL POST:/admin/activity/goods/delete
     * @param Request $request
     * @param array ids 奖品ID
     * @return mixed
     */
    public function delete(Request $request){
        $params =$request->only(['ids']);
        if (!array_key_exists('ids',$params) ||empty($params['ids'])) {
            return $this->error('请选择要删除的活动');
        }
        $result = AwardGoods::whereIn('id',$params['ids'])->delete();
        if ($result === false) {
            return  $this->error('删除失败');
        }
        return $this->success('删除成功');
    }

    /**
     * 修改排序
     * URL POST:/admin/activity/goods/updateSort
     * @param Request $request
     * @param int id
     * @param int sort 排序值
     * @return mixed
     */
    public function updateSort(Request $request){
        $params =$request->only(['id','sort']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少ID');
        }
        $sort = isset($params['sort']) ? $params['sort'] : 1;
        $detail = AwardGoods::find($params['id']);
        if (!$detail) {
            return $this->error('奖品不存在');
        }
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['sort'=>$sort];
        $result = AwardGoods::modify($where,$field);
        if ($result === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 是否显示
     * URL POST:/admin/activity/goods/updateStatus
     * @param Request $request
     * @param int id 奖品ID
     * @return mixed
     */
    public function updateStatus(Request $request){
        $params = $request->only(['id']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少奖品ID');
        }
        $trader = AwardGoods::find($params['id']);
        if (!$trader) {
            return $this->error('奖品不存在');
        }
        $status = $trader->status == 1 ? 2 : 1;
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['status'=>$status];
        $res = AwardGoods::modify($where,$field);
        if ($res === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

}